package push.tools.service.service.qycg;


import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import push.tools.service.config.network.OkHttpClientConfig;
import push.tools.service.constant.ApiUrl;

import java.util.List;

@Service
public class CookieService {
    private static final Logger logger = LoggerFactory.getLogger(CookieService.class);

    // 账号
    private static final String userAccount = "V9f3MA6zrw4EgCKhCqZ0Mg==";
    // 密码
    private static final String userPassword = "gb48S6zqJOCbG5hoMYbrDQ==";
    //获取cookies
    private static final String getCookieUrl = ApiUrl.loginUrl + "?" + "userAccount=" + userAccount + "&" + "userPassword=" + userPassword;

    @Autowired
    public OkHttpClient okHttpClient;

    public String getCookie() {
        Request request = OkHttpClientConfig.getRequest(getCookieUrl);
        try (Response response = okHttpClient.newCall(request).execute()) {
            String respString = response.body().string();
            String[] s1 = getStrings(respString, response);
            logger.warn("获取清远城管cookie成功：{}", s1[0]);
            return s1[0];
        } catch (Exception e) {
            throw new RuntimeException("获取清远城管cookie失败:" + e.getMessage());
        }
    }

    private static String[] getStrings(String respString, Response response) {
        if (respString.isEmpty()) {
            throw new RuntimeException("获取清远城管cookie失败:响应为空");
        }
        if (!respString.contains("true")) {
            throw new RuntimeException("获取清远城管cookie失败:" + respString);
        }
        Headers headers = response.headers();
        List<String> cookies = headers.values("Set-Cookie");
        if (cookies.isEmpty()) {
            throw new RuntimeException("获取清远城管cookie失败:Set-Cookie为空");
        }
        //登陆成功
        String s = cookies.get(0);
        return s.trim().replaceAll(" ", "").split(";");
    }
}
